<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// | 该文件的开源协议以所在项目的LICENSE文件为准，请遵守开源协议要求
// +----------------------------------------------------------------------
// | 站点管理
// +----------------------------------------------------------------------
namespace app\cms\http\api;

use app\admin\attributes\auth;
use app\cms\helper\cache;
use app\cms\model\SiteModel;
use Inphp\Core\Modules;
use Inphp\Core\Object\Message;
use Inphp\Core\Util\Str;

class site
{
    /**
     * 登陆账号的UID
     * @var int
     */
    public int $uid = 0;

    /**
     * 获取站点详情
     * @return Message
     */
    public function index(): Message
    {
        $id = GET("id");
        $id = is_numeric($id) && $id > 0 ? ceil($id) : 0;
        if ($id <= 0) {
            return httpMessage("站点ID无效");
        }
        $item = SiteModel::getRowByPrimaryKey($id);
        if (empty($item)) {
            return httpMessage("未找到站点数据");
        }
        //
        $item["logo"] = attachmentUrl($item["logo"]);
        return httpMessage($item);
    }

    /**
     * 获取站点列表
     * @param array|null $params
     * @return array
     */
    public function list(?array $params = null): array
    {
        //参数
        $params = $params ?? getClient()->get;
        //构建查询
        $db = SiteModel::emptyQuery("s")
            ->select("s.*");
        if ($sso = Modules::getModule("sso")) {
            $db->leftJoin(\app\sso\model\UserModel::tableName()." u", "s.uid=u.uid")
                ->addSelect([
                    "u.face, u.nickname, u.username, u.phone"
                ]);
        }
        //站点状态
        $state = $params["state"] ?? null;
        $state = $state == 1 || $state == '0' ? $state : null;
        if (!is_null($state)) {
            $db->where("s.state", $state);
        }
        //默认站点
        $default = $params["default"] ?? 0;
        if ($default == 1) {
            $db->where("s.default", 1);
        }
        //搜索
        $keyword = $params["keyword"] ?? null;
        if (!empty($keyword)) {
            $db->whereLike("s.name", $keyword);
        }
        //排除ID
        $excludeId = $params["excludeId"] ?? "";
        if (!empty($excludeId)) {
            $exId = [];
            $excludeId = is_array($excludeId) ? $excludeId : explode(",", $excludeId);
            foreach ($excludeId as $id) {
                if (is_numeric($id) && $id > 0 && !in_array(ceil($id), $exId)) {
                    $exId[] = ceil($id);
                }
            }
            if (!empty($exId)) {
                $db->whereNotIn("s.id", join(",", $exId));
            }
        }
        //行数
        $rows = $db->rows();
        //当前页数
        $page = $params["page"] ?? 1;
        $page = is_numeric($page) && $page > 0 ? ceil($page) : 1;
        //总页数
        $pages = 1;
        //列表数据
        $list = [];
        if ($rows > 0) {
            $total = $params["total"] ?? 30;
            $total = $total == 'max' ? $rows : $total;
            $total = is_numeric($total) && $total > 0 ? $total : 30;
            $pages = ceil($rows / $total);
            $page = $page > $pages ? $pages : $page;
            $offset = $total * ($page - 1);
            $list = $db->orderBy("s.id", "desc")->get($total, $offset);
            foreach ($list as &$item)
            {
                if ($sso && $item['uid'] > 0) {
                    $item['nickname'] = decodeNickname($item['nickname']);
                    $item['face'] = attachmentUrl($item['face']);
                }
                $item['logo'] = attachmentUrl($item['logo']);
                //链接
                $item["url"] = ($item["https"] == 1 ? "https://" : "http://").$item["host"];
            }
        }
        //返回列表数据，包含行数、页码、总页数、数据列表
        return compact("rows", "page", "pages", "list");
    }

    /**
     * 保存站点
     * @return Message
     */
    #[auth("cms/site")] public function save(): Message
    {
        //站点标志
        $logo = POST("logo");
        $logo = !empty($logo) ? parseUploadFilesUrl($logo) : null;
        $logo = is_array($logo) ? $logo[0] : $logo;
        //域名host
        $host = POST("host");
        $host = !empty($host) ? Str::trim($host) : null;
        if (empty($host)) {
            return httpMessage("缺少域名");
        }
        $host = Str::deletePrefix($host, ["https://", "http://"]);
        if (stripos($host, "/") !== false) {
            return httpMessage("域名格式错误");
        }
        if (stripos($host, ".") === false) {
            return httpMessage("域名格式错误");
        }
        //
        $https = POST("https");
        $https = $https == 1 ? 1 : 0;
        //名称
        $name = POST("name");
        $name = !empty($name) ? Str::trim($name) : null;
        if (empty($name)) {
            return httpMessage("缺少站点名称");
        }
        if (mb_strlen($name) < 1 || mb_strlen($name) > 20) {
            return httpMessage("站点名称请控制在20个字以内");
        }
        //默认站点
        $default = POST("default");
        $default = $default == 1 ? 1 : 0;
        //状态
        $state = POST("state");
        $state = $state == 1 ? 1 : 0;
        //使用的模板
        $template = POST("template");
        $template = !empty($template) ? Str::trim($template) : "default";

        //关键词
        $keyword = POST("keyword");
        $keyword = !empty($keyword) ? Str::trim($keyword) : null;
        $keyword = !empty($keyword) && mb_strlen($keyword) > 100 ? mb_substr($keyword, 0, 100) : $keyword;
        //摘要
        $description = POST("description");
        $description = !empty($description) ? trim($description) : null;
        $description = !empty($description) && mb_strlen($description) > 120 ? mb_substr($description, 0, 120) : $description;
        //附加HTML代码
        $html = POST("html");
        $html = !empty($html) ? $html : null;
        //备案号
        $icp = POST("icp");
        $icp = !empty($icp) ? Str::trim($icp) : null;

        $id = POST("id");
        $id = is_numeric($id) && $id > 0 ? ceil($id) : 0;

        //组织数据
        $data = [
            "uid"       => $this->uid,
            "logo"      => $logo,
            "host"      => $host,
            "https"     => $https,
            "name"      => $name,
            "default"   => $default,
            "state"     => $state,
            "template"  => $template,
            "keyword"   => $keyword,
            "description" => $description,
            "html"      => $html,
            "icp"       => $icp
        ];
        //host 不可重复
        $exists = SiteModel::emptyQuery()->where("id", "!=", $id)->where("host", $host)->first();
        if (!empty($exists)) {
            return httpMessage("同域名的站点已存在");
        }
        //名称 也不可重复
        $exists = SiteModel::emptyQuery()->where("id", "!=", $id)->where("name", $name)->first();
        if (!empty($exists)) {
            return httpMessage("同名站点已存在");
        }
        $db = SiteModel::emptyQuery();
        if ($id > 0) {
            $db->where("id", $id)->set($data);
            if (!$db->update()) {
                return httpMessage("保存失败");
            }
        } else {
            if (!$db->insert($data)) {
                return httpMessage("添加站点失败");
            }
            $id = $db->getLastInsertId();
        }
        //如果设置了默认
        if ($default === 1) {
            @SiteModel::emptyQuery()->where("id", "!=", $id)->update(["default" => 0]);
        }
        //更新缓存
        @$this->cache();
        return httpMessage(0, "操作成功");
    }

    /**
     * 修改站点状态
     * @return Message
     */
    #[auth("cms/site")] public function switch(): Message
    {
        $id = POST("id");
        $id = is_numeric($id) && $id > 0 ? ceil($id) : 0;
        if ($id <= 0) {
            return httpMessage("ID参数无效");
        }
        $db = SiteModel::emptyQuery()->where("id", $id)->setRaw("state", "if(`state`=1, 0, 1)");
        if ($db->update()) {
            //更新缓存
            @$this->cache();
            return httpMessage(0, "操作成功");
        }
        return httpMessage("操作失败");
    }

    /**
     * 删除站点
     * @return Message
     */
    #[auth("cms/site")] public function delete(): Message
    {
        //
        $id = POST("id");
        $id = is_numeric($id) && $id > 0 ? ceil($id) : 0;
        if ($id <= 0) {
            return httpMessage("ID参数无效");
        }
        $db = SiteModel::emptyQuery()->where("id", $id);
        if ($db->delete()) {
            //更新缓存
            @$this->cache();
            return httpMessage(0, "删除了{$db->getAffectRows()}行数据");
        }
        return httpMessage("删除失败");
    }

    /**
     * 缓存站点数据到文件
     * 前端读取时，直接从缓存里边读取
     * 使用HOST作为KEY值
     * @return Message
     */
    public function cache(): Message
    {
        SiteModel::cache();
        return httpMessage(0, "操作成功");
    }
}